//
//  NSString+HFString.m
//  mentor
//
//  Created by 孙宏峰的MacPro on 2018/7/8.
//  Copyright © 2018年 孙宏峰的MacPro. All rights reserved.
//

#import "NSString+HFString.h"

@implementation NSString (HFString)

-(NSString *)trim{
    NSString *str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString * strResult = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    return strResult;
}

#pragma mark - 截取URl中参数
- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    //添加防御
    if (!urlStr || [urlStr trim].length == 0) {
        return nil;
    }
    
    // 查找参数
    if ([urlStr rangeOfString:@"?"].location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSArray * arr = [urlStr componentsSeparatedByString:@"?"];
    if ([arr count] != 2) {
        return nil;
    }
    
    NSString *parametersString = arr[1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil ) {
                continue;
            }
            
            // 设置值
            [params setValue:value forKey:key];
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}

+(NSString *)noNull:(NSString *)string{
    if ([[string class] isSubclassOfClass:[NSString class]]) {
        if ((string == nil) || ([string length] == 0) || [string isEqualToString:@"<null>"] || [string isEqualToString:@"(null)"]||([string isEqualToString:@"<nil>"])||([string isEqualToString:@"(nil)"])) {
            string = @"";
        }
        return string;
    } else {
        return @"";
    }
}

@end
